package com.lailai.service.impl;

import com.lailai.metadata.BizObjectTable;
import com.lailai.metadata.Property;
import com.lailai.service.BizObjectSchemaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author lgr
 * @Date 2025/9/18
 * @Description 业务对象表结构实现类
 * @Email 983105834@qq.com
 */
@Service
public class BizObjectSchemaServiceImpl implements BizObjectSchemaService {
    @Autowired
    private DataSource dataSource;

    @Override
    public BizObjectTable getSchema(String schemaCode) {
        BizObjectTable table = new BizObjectTable();
        table.setId(schemaCode);
        table.setTableCode(schemaCode);
        table.setName(schemaCode + " 表");
        List<Property> properties = new ArrayList<>();

        // 从数据库查询表结构信息
        try (Connection conn = dataSource.getConnection();
             PreparedStatement stmt = conn.prepareStatement(
                     "SELECT COLUMN_NAME, COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ?")) {

            stmt.setString(1, schemaCode);
            ResultSet rs = stmt.executeQuery();

            while (rs.next()) {
                Property property = new Property();
                property.setId(rs.getString("COLUMN_NAME"));
                // 可以根据需要添加更多字段信息
                properties.add(property);
            }
        } catch (SQLException e) {
            // 处理异常
        }

        table.setProperties(properties);
        return table;
    }

    @Override
    public List<BizObjectTable> getAllSchemas() {
        return new ArrayList<>();
    }

}
